package com.heima.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        InputStream in = null;
        try {
            //1.读取配置文件
            String source = "mybatis-config.xml";
            in = Resources.getResourceAsStream(source);
            //2.解析配置文件
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取sqlSession
    public static SqlSession getSqlSession(){
        // true  自动提交
        return sqlSessionFactory.openSession(true);
    }

    //获取sqlSession
    public static SqlSession getSqlSession(boolean b){
        return sqlSessionFactory.openSession(b);
    }

}
